package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service
@Slf4j
public class OrderPayedListener {

    @Autowired
    RabbitService rabbitService;
    @Autowired
    OrderInfoService orderInfoService;


   @RabbitListener(queues = RabbitConstant.QUEUE_ORDER_PAYED)
    public void handle(Message message, Channel channel) throws IOException {
        //
       long deliveryTag = message.getMessageProperties().getDeliveryTag();
       String json = new String(message.getBody());
       try {
           Map<String, String> stringStringMap = JSONs.stringToObj(json, new TypeReference<Map<String, String>>() {
           });
           //已支付修改订单状态
           log.info("正在修改订单已支付:{}",stringStringMap.get("out_trade_no"));
           orderInfoService.updateOrderStatusPayed(stringStringMap);

           channel.basicAck(deliveryTag, false);
       } catch (Exception e) {
            //重试
           e.printStackTrace();
           log.info("消息{}发送失败",json);
           rabbitService.retry(deliveryTag, channel, json, 5);
       }
    }
}
